import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/21 15:03
 * @description 加起来，子岛屿即为数字为2的岛屿
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] grid1 = {{1,1,1,0,0}, {0,1,1,1,1}, {0,0,0,0,0}, {1,0,0,0,0},
                {1,1,0,1,1}},
                grid2 = {{1,1,1,0,0}, {0,0,1,1,1}, {0,1,0,0,0}, {1,0,1,1,0},
                        {0,1,0,1,0}};
        System.out.println(solution.countSubIslands(grid1, grid2));
    }
    private static int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    private int value;
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid1.length, n = grid1[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j] == 1) {
                    grid2[i][j] += grid1[i][j];
                }

            }
        }
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j] == 2 ) {
                    value = 1;
                    dfs(grid2, i, j);
                    count += value;
                }
            }
        }
        return count;
    }
    public void dfs(int[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {
            return;
        }
        if (grid[i][j] == 1) {
            // grid2中 2旁边还有1，那么说明无法被grid1中包围
            value = 0;
            return;
        }
        grid[i][j] = 0;
        for(int[] dir : dirs ) {
            int ni = i + dir[0], nj = j + dir[1];
            dfs(grid, ni, nj);
        }
    }
}
